package homework3;

import java.util.Random;

class GuessNumberGame {
    private volatile boolean numberSet = false;
    private volatile boolean guessCorrect = false;
    private volatile int number;

    public void setNumber() {
        if (!numberSet) {
            Random random = new Random();
            number = random.nextInt(100) + 1;
            numberSet = true;
            System.out.println("已随机生成一个1~100之间的整数，请开始猜数");
        }
    }

    public void guessNumber(int guess) {
        if (numberSet && !guessCorrect) {
            if (guess > number) {
                System.out.println("猜大了");
            } else if (guess < number) {
                System.out.println("猜小了");
            } else {
                System.out.println("猜对了");
                guessCorrect = true;
            }
        }
    }

    public static void main(String[] args) {
        GuessNumberGame game = new GuessNumberGame();

        Thread thread1 = new Thread(() -> {
            game.setNumber();
            while (!game.guessCorrect) {
                // 等待猜数结果
                Thread.yield();
            }
        });

        Thread thread2 = new Thread(() -> {
            while (!game.numberSet) {
                // 等待设置猜测的数字
                Thread.yield();
            }

            Random random = new Random();
            while (!game.guessCorrect) {
                int guess = random.nextInt(100) + 1;
                System.out.println("猜测数字：" + guess);
                game.guessNumber(guess);
                // 等待提示结果
                Thread.yield();
            }
        });

        thread1.start();
        thread2.start();
    }
}